/**
 * @description 通告services
 */

const {
    User,
    Notice
} = require('../db/model/index')
const {
    noticeEnroll
} = require('./_format')

/**
 * @description 在数据库创建Notivce
 */
async function createNotice({
    userId,
    title,
    content,
    type,
    province,
    city,
    phone,
    weChat,
    activityTime,
    createTime
}) {
    const result = await Notice.create({
        userId,
        title,
        content,
        type,
        province,
        city,
        phone,
        weChat,
        activityTime,
        createTime
    })
    return result
}

/**
 * @description 查询通告列表
 * @param {*} param0 
 */
async function getNoticeList({
    province,
    city,
    type
}) {
    let whereData = {}
    if (province != '全国') {
        whereData['province'] = province
    }
    if (city != '全部') {
        whereData['city'] = city
    }
    if (type != '全部') {
        whereData['type'] = type
    }
    console.log(JSON.stringify(whereData), 'whereData');

    let result = await Notice.findAndCountAll({
        attributes: {
            exclude: ['phone', 'weChat', 'createdAt', 'updatedAt']
        },
        order: [
            ['id', 'desc']
        ],
        include: {
            model: User,
            attributes:['id','avatar','userName']
        },
        where: whereData
    })
    result.rows = result.rows.map(val => { //根据日期判断是否可报名 1可报名
        val.status = noticeEnroll(val.activityTime)
        return val
    })

    return result
}

module.exports = {
    createNotice,
    getNoticeList
}